from fastapi import FastAPI

app = FastAPI()
"""3.查询参数"""

fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]


@app.get("/items/")
async def read_items(skip: int = 0, limit: int = 10):
    """
    查询字符串是键值对的集合，这些键值对位于 URL 的 ? 之后，以 & 分隔。
    ?skip=0&limit=10
    :param skip:
    :param limit:
    :return:
    """
    return fake_items_db[skip:skip + limit]


# 默认值
"""
http://127.0.0.1:8000/items/ == http://127.0.0.1:8000/items/?skip=0&limit=10

http://127.0.0.1:8000/items/?skip=20
查询参数的值就是：

skip=20：在 URL 中设定的值
limit=10：使用默认值
"""


# 可选参数
@app.get("/items/{item_id}")
async def read_item(item_id: str, q: str | None = None):
    if q:
        return {"item_id": item_id, "q": q}
    return {"item_id": item_id}


# 查询参数类型转换
@app.get("/items/{item_id}")
async def read_item(item_id: str, q: str | None = None, short: bool = False):
    item = {"item_id": item_id}
    if q:
        item.update({"q": q})
    if not short:
        item.update(
            {"description": "This is an amazing item that has a long description"}
        )
    return item


"""
http://127.0.0.1:8000/items/foo?short=1
http://127.0.0.1:8000/items/foo?short=True
http://127.0.0.1:8000/items/foo?short=true
http://127.0.0.1:8000/items/foo?short=on
http://127.0.0.1:8000/items/foo?short=yes
"""


# 多个路径和查询参数
@app.get("/users/{user_id}/items/{item_id}")
async def read_user_item(
        user_id: int, item_id: str, q: str | None = None, short: bool = False
):
    """
    http://127.0.0.1:8000/users/1/items/1
    http://127.0.0.1:8000/users/1/items/1?short=True
    http://127.0.0.1:8000/users/1/items/1?q=abc&short=True
    :param user_id:
    :param item_id:
    :param q:
    :param short:
    :return:
    """
    item = {"item_id": item_id, "owner_id": user_id}
    if q:
        item.update({"q": q})
    if not short:
        item.update(
            {"description": "This is an amazing item that has a long description"}
        )
    return item


# 必选查询参数

@app.get("/must/{item_id}")
async def must_item(item_id: str, needy: str):
    """
    needy: str | None = None
    http://127.0.0.1:8000/must/1
    http://127.0.0.1:8000/must/1?needy=abc
    :param item_id:
    :param needy:
    :return:
    """
    item = {"item_id": item_id, "needy": needy}
    return item


@app.get("/must/{item_id}")
async def read_user_item(
        item_id: str, needy: str, skip: int = 0, limit: int | None = None
):
    """
    needy，必选的 str 类型参数
    skip，默认值为 0 的 int 类型参数
    limit，可选的 int 类型参数
    :param item_id:
    :param needy:
    :param skip:
    :param limit:
    :return:
    """
    item = {"item_id": item_id, "needy": needy, "skip": skip, "limit": limit}
    return item
